/**
 * 城市选择模块
 * @author Levin
 * @version 1.0
 */
JF.M("tuanCity",(function($){

	var p={},pub={};

	/**
	 * 城市数据
	 */
	p.cityData={
		isInit:false,
		cache:null,
		url:'js/city.js',
		tpl_item:'<li><a href="#" rel="%p_name%">%cn_name%<s></s></a></li>',
		tpl_hd:'<h2 class="tit">%alpha% %name%</h2>',
		setup:function(){
			var me=this;
			$("#p31").bind("pageshow",function(){
				if(me.isInit) return;

				me.pull(me.buildUI);

			});

		},
		pull:function(cbk){
			if(this.cache){
				cbk.call(this,this.cache);
				return;
			};
			var me=this;
			$.ajax({
				url: me.url,
				dataType: 'json',
				success:function(d){
					if(cbk){
						cbk.call(me,d);
					}
				},
				error:function(){
					if(cbk){
						cbk.call(me,false);
					}
				}
			});
		},//pull
		buildUI:function(d){
			if(!d) return;
			if((!d.data) || (!d.data.length) ) return;
			this.cache=d;
			
			var $d=$("#J_citylist"),
				me=this,
				html="",
				tempArr;

			d=me.parseData(d.data);
			
			//console.log(d);

			for(var c in d){
				if(!c) continue;
				if(d[c].length===0) continue;

				tempArr=d[c];
				
				for(var i =0 ;i<tempArr.length;i++){
					html+=JF.EvalTpl(me.tpl_hd,{"alpha":c,"name":tempArr[i].name});
					html+='<ul class="list_1">';
					for(var j = 0 ; j<tempArr[i].items.length; j++ ){
						html+=JF.EvalTpl(me.tpl_item,tempArr[i].items[j]);
					}//for

					html+='</ul>';

				}//for

			};//for

			$d.append(html);

			//refresh iscroll
			var iscr=JF.iscroll.Get($("#p31").find(":jqmData(iscroll='true')")[0].id);
			iscr.val.refresh();

			this.isInit=true;

		},//buildUI
		//对城市数据进行分组
		parseData:function(d){
			var data={"A":[],"B":[],"C":[],"D":[],"E":[],"F":[],"G":[],"H":[],"I":[],"J":[],"K":[],"L":[],"M":[],"N":[],"O":[],"P":[],"Q":[],"R":[],"S":[],"T":[],"U":[],"V":[],"W":[],"X":[],"Y":[],"Z":[]};
			var temp=temp1=obj=null;
			for(var i=0;i<d.length;i++){
				obj=d[i];
				if(obj.alpha==""){
					continue;
				};
				temp=data[obj.alpha];
				temp1={};
				if(temp.length==0){
					temp1.name=obj.province_name;
					temp1.items=[obj];
					data[obj.alpha].push(temp1);
					continue;
				};

				//判断省名
				var provinceExists=false;
				for(var j=0;j<temp.length;j++){
					if(temp[j].name===obj.province_name){
						provinceExists=true;
						temp[j].items.push(obj);
					}
				}
				if(!provinceExists){
					temp1.name=obj.province_name;
					temp1.items=[obj];
					data[obj.alpha].push(temp1);
				}

			}//for

			return data;

		}//parseData
	};//cityData

	pub.onLoad=function(){
		p.cityData.setup();
	};

	return pub;

})(jQuery));